package com.dxy.df.utils;

import com.alibaba.fastjson.JSONObject;
import com.dxy.df.core.model.Rs;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public final class WebUtil {

    private static final Logger LOGGER = LoggerFactory.getLogger(WebUtil.class);

    public static HttpServletRequest getHttpServletRequest() {
        if (null != RequestContextHolder.getRequestAttributes()) {
            return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        } else {
            return null;
        }
    }


    public static boolean loginFailResponse(ServletResponse response) {
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        try {
            httpResponse.setContentType("application/json;charset=utf-8");
            Rs r = Rs.error(1001, "未登录，请先登录!");
            httpResponse.getWriter().print(JSONObject.toJSONString(r));
        } catch (IOException e) {
            LOGGER.error(e.getMessage());
        }
        return false;
    }


    public static String getRequestTicket(HttpServletRequest httpRequest) {
        //从header中获取ticket
        String ticket = httpRequest.getHeader("ticket");
        //如果header中不存在ticket，则从参数中获取ticket
        if (StringUtils.isEmpty(ticket)) {
            ticket = httpRequest.getParameter("ticket");
        }
        return ticket;
    }

    public static String getRequestToken(HttpServletRequest httpRequest) {
        //从header中获取token
        String token = httpRequest.getHeader("token");
        //如果header中不存在ticket，则从参数中获取ticket
        if (StringUtils.isEmpty(token)) {
            token = httpRequest.getParameter("token");
        }
        return token;
    }


}